package vn.smartoffice.promail.config;

import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import scala.concurrent.duration.Duration;
import akka.actor.ActorSystem;

/**
 * The Class AkkaWebInitializer.
 *
 * @author Nguyen Duc Dung
 * @since 8/1/14 10:46 AM
 */
@Slf4j
public class AkkaWebInitializer implements ServletContextListener {

    @Autowired
    private ActorSystem actorSystem;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //Get the actor system from the spring context
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (actorSystem != null) {
            log.info("Killing ActorSystem as a part of web application ctx destruction.");
            actorSystem.shutdown();
            actorSystem.awaitTermination(Duration.create(15, TimeUnit.SECONDS));
        } else {
            log.warn("No actor system loaded, yet trying to shut down. Check AppContext config and consider if you need this listener.");
        }
    }
}
